<template>
  <div>
    <!--条件筛选-->
    <TopFilter ref="topFilter" :list="topFilterList" :cols="3" labelWidth="110" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
    <!-- table -->
    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :isSelectColumn="false"
      :onRowSelectChange="selectChange"
      :onColumnsChange="columns => (this.columns = columns)"
      :isExportExcel2="true"
      :exportFileName="'备件基本信息.xlsx'"
    >
      <template slot="controls">
        <el-button size="small" type="primary" @click="openimportPjDialog()">导 入</el-button>
        <!--        <el-button size="small" type="primary" @click="downloadTemplate">下载导入模板</el-button>-->
        <!-- <el-button size="small" type="primary" @click="importPartInfo">导出</el-button> -->
      </template>
    </FilterTable>

    <!-- 编辑窗口 -->
    <Drawer :visible.sync="visibleDrawer" :title="title" :width="1000" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <part-info v-model="initData" :type="handleType" :rowData="formData" @close="infoClose" />
    </Drawer>

    <BaseDialog
      style="min-height: 80vh;"
      :visible.sync="visibleImportPeij"
      width="80vw"
      title="备件导入"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '50px' }"
    >
      <ExcelImport :onBeforeDownloadTemp="setParts" ref="import" template-file-name="备件主数据导入模板.xlsx" :importRules="importRules" :onComplete="importComplete" @close="visibleImportPeij = false" />
    </BaseDialog>
    <!--    :onBeforeDownloadTemp="setParts"-->
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { exportExcelFile } from '@/utils/index';
import { exportExcel,getpartinfo, importPartPrice, findModelList,findPartTypeList } from '@/api/partsmanage/partinfos/partInfoManage/index';
import partInfo from './partInfo';
import ExcelImport from '@/components/ExcelImport';

export default {
  name: 'partInfoManage',
  components: { partInfo, ExcelImport },
  mixins: [dictionary],
  data() {
    return {
      topFilterList: this.createTopFilterList(),
      columns: this.createTableColumns(),
      fetchApi: getpartinfo,
      fetchParams: { xhrAbort: true },
      visibleDrawer: false,
      visibleImportPeij: false,
      handleType: '',
      formData: {},
      title: '',
      initData: {},
      partinfos: {},
      rowSelectData: [],
      importRules: [
        { prop: 'bjxmbh', title: '备件代码', rule: { required: true, message: '备件代码不能为空' } },
        // { prop: 'material', title: '物料组' },
        { prop: 'modelCode', title: '适用车型代码' },
        { prop: 'bjxszx', title: '销售包装量' },
        { prop: 'bjdebz', title: '是否紧急件' },
        { prop: 'bjtsbz', title: '是否特殊件' },
        { prop: 'bjxsbz', title: '销售标识' },
        { prop: 'bjpjfl', title: '备件类别' },
        { prop: 'remark', title: '备注' }
      ],
      modelList:[],
      partTypeList:[]
    };
  },
  created(){

      findModelList().then(res =>{
        this.modelList = res.data;
        this.topFilterList.find(x=>x.fieldName=='bjsycx').itemList = this.modelList;
      });
      findPartTypeList().then(res =>{
        this.partTypeList = res.data;
        this.topFilterList.find(x=>x.fieldName=='bjpjfl').itemList = this.partTypeList;
      });

  },
  methods: {
    importPartInfo(){
      let json = {};
      this.topFilterList.forEach(x => {
        this.$set(json, x.fieldName, x.initialValue);
      });
      console.log(json);
      exportExcel(json).then(res =>{
        exportExcelFile(res.data,"备件主信息")
      })
    },
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '备件代码',
          fieldName: 'bjxmbh'
        },
        {
          type: 'INPUT',
          label: '备件名称',
          fieldName: 'bjzwmc'
        },
        {
          type: 'SELECT',
          label: '是否备件图片',
          fieldName: 'hasPics',
          placeholder: '请选择...',
          itemList: this.createDictList('1004')
        },
        {
          type: 'SELECT',
          label: '备件类别',
          fieldName: 'bjpjfl',
          placeholder: '请选择...',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '是否有3C证书',
          fieldName: 'has3C',
          placeholder: '请选择...',
          itemList: this.createDictList('1004')
        },
        {
          type: 'SELECT',
          label: '销售标识',
          fieldName: 'bjxsbz',
          placeholder: '请选择...',
          itemList: this.createDictList('1004')
        },
        {
          type: 'SELECT',
          label: '是否特殊',
          fieldName: 'bjtsbzMark',
          placeholder: '请选择...',
          itemList: this.createDictList('1004')
        },
        {
          type: 'SELECT',
          label: '是否紧急',
          fieldName: 'bjdebzMark',
          placeholder: '请选择...',
          itemList: this.createDictList('1004')
        },
        {
          type: 'RANGE_DATE',
          fieldName: 'updatedAtStart|updatedAtEnd',
          label: '更新时间',
          initialValue: [],
          dateType: 'daterange'
        },
        {
          type: 'SELECT',
          label: '适用车型',
          fieldName: 'bjsycx',
          placeholder: '请选择...',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '物料组',
          fieldName: 'material',
          placeholder: '请选择...',
          itemList: this.createDictList('3054')
        },

      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.editHandle(props.row, 'edit')}>
                  编辑
                </el-button>
                <el-divider direction="vertical" />
                <el-button size="mini" type="text" onClick={() => this.editHandle(props.row, 'show')}>
                  详情
                </el-button>
              </div>
            );
          }
        },
        {
          title: '备件代码',
          dataIndex: 'bjxmbh',
          width: 150,
          sorter: true
        },
        {
          title: '备件名称',
          dataIndex: 'bjzwmc',
          sorter: true
        },
        {
          title: '物料组',
          dataIndex: 'material',
          sorter: true,
          dictItems:this.createDictList('3054'),
        },
        {
          title: '服务商进价',
          dataIndex: 'xs',
          sorter: true,
          precision: 2,
          numberFormat: true
        },
        {
          title: '终端销售价',
          dataIndex: 'ls',
          sorter: true,
          precision: 2,
          numberFormat: true
        },
        {
          title: '销售标识',
          dataIndex: 'bjxsbz',
          dictItems:this.createDictList('1004'),
          sorter: true
        },
        {
          title: '是否特殊',
          dataIndex: 'bjtsbz',
          dictItems:this.createDictList('1004'),
          sorter: true
        },
        {
          title: '是否紧急',
          dataIndex: 'bjdebz',
          dictItems:this.createDictList('1004'),
          sorter: true
        },
        {
          title: '备件类别',
          dataIndex: 'partTypeName',
          sorter: true
        },
        {
          title: '销售包装量',
          dataIndex: 'bjxszx',
          sorter: true
        },
        {
          title: '适用车型',
          dataIndex: 'bjsycxmc',
          dictItems: this.modelList,
          sorter: true
        },
        {
          title: '是否备件图片',
          dataIndex: 'hasPics',
          dictItems: this.createDictList('1004'),
          sorter: true

        },
        {
          title: '是否3C证书',
          dataIndex: 'has3C',
          dictItems: this.createDictList('1004'),
          sorter: true
        },
        // {
        //   title: '采购包装量',
        //   dataIndex: 'bjcgzx',
        //   sorter: true
        // },
        // {
        //   title: '采购标识',
        //   dataIndex: 'bjcgbz',
        //   dictItems: [
        //     { text: '是', value: 'Y' },
        //     { text: '否', value: 'N' }
        //   ],
        //   sorter: true
        // },
        {
          title: '更新人',
          dataIndex: 'updateUserInfo.userName',
          sorter: true
        },
        {
          title: '更新时间',
          dataIndex: 'updatedAt',
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          sorter: true
        }
      ];
    },
    selectChange(val) {
      console.log('val', val);
      this.rowSelectData = val;
    },
    editHandle(row, type) {
      if (type === 'edit') {
        this.title = '编辑';
      } else if (type === 'show') {
        console.log('主页面带入明细页面字段数据',row);
        this.title = '详情';
      }
      this.formData = row;
      this.handleType = type;
      this.visibleDrawer = true;
    },
    // 配件列表明细数据获取
    syncPjFun(details) {
      this.partinfos = details;
      console.info(details);
      console.info(partinfos);
    },
    downloadTemplate() {
      this.$confirm('下载模板', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          window.open('/static/tinymce/template/PartInfos.xls');
          this.$message({
            type: 'success',
            message: '下载成功!'
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    setParts(callback) {
      const data = [
        // {bjxmbh:"xxx",bjxszx:"1",bjdebz:"是/否",bjtsbz:"是/否",bjxsbz:"是/否",bjpjfl:"通用件",remark:"模板"}
        //取消适用车型导入维护
        {bjxmbh:"xxx",modelCode:"A,B,C",bjxszx:"1",bjdebz:"是/否",bjtsbz:"是/否",bjxsbz:"是/否",bjpjfl:"通用件",remark:"模板"}
      ]
      callback(data);
    },
    changeHandle(val) {
      this.fetchParams = Object.assign({}, val);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    /* 打开导入配件Dialog */
    openimportPjDialog() {
      this.visibleImportPeij = true;
    },
    //导入
    async importComplete(datas, callback) {
      const errorData = [];
      console.info(datas);
      datas.forEach((item, index1) => {
        const indexarr = [];
        datas.forEach((i, index2) => {
          if (i.bjxmbh === item.bjxmbh && i.bjpjsx === item.bjpjsx && index1 !== index2) {
            indexarr.push(index2 + 1);
          }
        });
        if (indexarr.length && item.xtsxrq < item.xtyxrq) {
          errorData.push({
            rownum: index1 + 1,
            errormsg: `与第${indexarr.join(',')}行备件信息重复;失效日期不能小于有效日期`
          });
        } else if (item.xtsxrq < item.xtyxrq) {
          console.info(item.xtsxrq);
          console.info(item.xtyxrq);
          errorData.push({
            rownum: index1 + 1,
            errormsg: `失效日期不能小于有效日期`
          });
        } else if (indexarr.length) {
          errorData.push({
            rownum: index1 + 1,
            errormsg: `与第${indexarr.join(',')}行备件信息重复`
          });
        }
        if (item.ls === '' && item.xs === '') {
          errorData.push({
            rownum: index1 + 1,
            errormsg: `服务商进价和终端销售价不能同时为空;`
          });
        }
      });
      if (errorData.length) {
        callback(errorData);
      } else {
        importPartPrice(datas).then(res => {
          if (res.resultCode == 200) {
            if (res.data.status) {
              this.visibleImportPeij = false;
              this.$notify.success({ title: '提示信息', message: '批量导入成功' });
              this.fetchParams = Object.assign({}, this.fetchParams);
              callback();
              this.infoClose('refresh');
            } else {
              callback(res.data.errorData);
            }
          } else {
            callback([{ errormsg: '服务器运行异常' }]);
          }
        });
      }
    },
    infoClose(rData) {
      this.visibleDrawer = false;
      console.info(rData);
      if (rData.type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    }
  }
};
</script>

<style scoped></style>
